using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
    [Header("Player")]
    public CharacterController player;
    public Animator anim;
    private Vector3 Direction;
    public float Speed;

    [Header("Jump")]
    public float jumpHeight;
    public bool jumpTime;
    public float gravity = -19.62f;
    private Vector3 forceY;

    public Transform detector;
    public LayerMask layerFloor;
    public bool isOnFloor;

    [Header("Camera")]
    public Transform currentCamera;
    public float rotationSmooth;
    private float rotationSpeed;
    float vision;
    float angles;

    private void FixedUpdate()
    {
        isOnFloor = Physics.CheckSphere(detector.position, 0.3f, layerFloor);
    }

    void Update()
    {
        float horizontal = Input.GetAxisRaw("Horizontal");
        float vertical = Input.GetAxisRaw("Vertical");
        Direction = new Vector3(horizontal, 0f, vertical);
        vision = Mathf.Atan2(Direction.x, Direction.z) * Mathf.Rad2Deg + currentCamera.eulerAngles.y;
        angles = Mathf.SmoothDampAngle(transform.eulerAngles.y, vision, ref rotationSpeed, rotationSmooth);

        forceY.y += gravity * Time.deltaTime;
        player.Move(forceY * Time.deltaTime);

        Run();
        Movement();
        Control();
    }

    void Movement()
    {
        if (Direction.magnitude >= 0.1f)
        {
            transform.rotation = Quaternion.Euler(0f, angles, 0f);
            Vector3 newDirection = Quaternion.Euler(0f, vision, 0f) * Vector3.forward;
            player.Move(newDirection * Speed * Time.deltaTime);
            anim.SetBool("Walk", true);
        }

        if (Direction.magnitude < 0.1f)
        {
            anim.SetBool("Walk", false);
        }
    }

    void Run()
    {
        if (Input.GetKey(KeyCode.LeftShift) && Direction.magnitude > 0.1f)
        {
            transform.rotation = Quaternion.Euler(0f, angles, 0f);
            Vector3 newDirection = Quaternion.Euler(0f, vision, 0f) * Vector3.forward;
            player.Move(newDirection * Speed * Time.deltaTime);
            anim.SetBool("Run", true);
        }
        else {
            anim.SetBool("Run", false);
        }
    }

    public void JumpTime(bool releaseJump)
    {
        jumpTime = releaseJump;
    }

    void Control()
    {
        if (Input.GetKeyDown(KeyCode.Space) & isOnFloor == true & jumpTime == false)
        {
            anim.SetBool("Jump", true);
            forceY.y = Mathf.Sqrt(jumpHeight * -2 * gravity);
        }
        else
        {
            anim.SetBool("Jump", false);
        }
    }
}
